package cn.test.rabbitmq.normal;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 *  RabbitMQ默认有一个exchange，叫default exchange，它用一个空字符串表示，它是direct exchange类型，
 *  任何发往这个exchange的消息都会被路由到routing key的名字对应的队列上，如果没有对应的队列，则消息会被丢弃。
 *  这就是为什么代码中channel执行basicPulish方法时，第二个参数本应该为routing key，却被写上了QUEUE_NAME。
 * @author hanchao
 * @date 2017/6/30 14:35
 */
public class DefaultDLXDirectProducer {
    private static final String QUEUE_NAME = "test-queue-dlx-fa";
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.1.170");
        factory.setUsername("admin");
        factory.setPassword("admin");
        factory.setVirtualHost("han");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        String message = "Hello RabbitMQ";

        AMQP.Exchange.DeclareOk exchange = channel.exchangeDeclare("dir", BuiltinExchangeType.DIRECT);

        //第二个参数，是否重启后依然存在（不存在会丢消息）restricted to this connection
        //第二个参数，是否是否私有 （只有你的应用程序才可以消费消息）
        //autoDelete 当最后一个消费者移除udall时候，队列自动删除
        Map<String,Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange","");
        arguments.put("x-dead-letter-routing-key","ztk-dead-letters");

        AMQP.Queue.DeclareOk dc = channel.queueDeclare(QUEUE_NAME, false, false, false, arguments);
        channel.queueBind(QUEUE_NAME,"dir","test-queue-dlx-fa");
        for (int i = 0; i < 1; i++) {
            channel.basicPublish("dir", "test-queue-dlx-fa", null, (message+i).getBytes("UTF-8"));
            Thread.sleep(10L);
        }
        //关闭通道和连接
        channel.close();
        connection.close();
    }
}
